package org.minproject.my_library_back.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.minproject.my_library_back.common.CommonResponse;
import org.minproject.my_library_back.domain.User;
import org.minproject.my_library_back.service.UserService;
import org.minproject.my_library_back.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author Lenovo
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-11-21 09:11:46
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public CommonResponse<User> getUserByUserid(String userid) throws Exception {
        User user = userMapper.selectById(userid);
        if (user == null) {
            return CommonResponse.createForSuccess("没有该userid的用户", null);
        }
        return CommonResponse.createForSuccess("查询成功", user);
    }

    @Override
    public CommonResponse<User> login(String userid, String password) {
        // 查询数据库获取用户信息
        User user = userMapper.selectById(userid);

        if (user == null) {
            return CommonResponse.createForSuccess("用户名不存在", null);
        }

        // 校验密码
        if (!user.getUserPassword().equals(password)) {
            {
                return CommonResponse.createForSuccess("密码错误", null);
            }
            }

            // 登录成功
            return CommonResponse.createForSuccess("登录成功", user);

        }

    @Override
    public CommonResponse<User> register(User user) {
        // 检查是否所有字段非空
        if (user.getUserId() == null || user.getUserName() == null || user.getUserPassword() == null || user.getUserPower() == null || user.getUserPicture() == null) {
            return CommonResponse.createForError("所有信息均不能为空");
        }

        // 检查用户是否已存在
        User existingUser = userMapper.selectById(user.getUserId());
        if (existingUser != null) {
            return CommonResponse.createForError("用户名已存在");
        }

        // 插入新用户数据到数据库
        int result = userMapper.insert(user); // 插入五个字段
        if (result > 0) {
            return CommonResponse.createForSuccess("用户注册成功", user);
        }

        return CommonResponse.createForError("用户注册失败");

    }

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUsers() {
        return userMapper.getUsers();
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public int deleteUser(int user_id) {
        return userMapper.deleteUser(user_id);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public List<User> getUsersByUserIdLike(int user_id) {
        return userMapper.getUsersByUserIdLike(user_id);
    }

}




